package burubaka.controller.bat;

import java.util.List;
import java.util.logging.Logger;

import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;

import burubaka.BurubakaConstants;
import burubaka.model.RaceCardHorse;
import burubaka.model.RaceInfo;
import burubaka.service.RaceCardHorseService;
import burubaka.service.RaceInfoService;

public class RaceCancelHorseController extends Controller {

	private static final Logger log = Logger.getLogger(RaceCancelHorseController.class.getName());
	private RaceCardHorseService raceCardHorseService = new RaceCardHorseService();
	private RaceInfoService raceInfoService = new RaceInfoService();

	@Override
	public Navigation run() throws Exception {
		RaceInfo raceInfo = raceInfoService.getCurrentRaceInfo();

		// すでにレース情報が登録されているかどうか判断
		if (raceInfo == null) {
			return null;
		}
		// 本登録かつキャンセルでもない場合
		if (raceInfo.getProgress() != BurubakaConstants.PROGRESS_RACECARD
				&& raceInfo.getProgress() != BurubakaConstants.PROGRESS_CANCEL) {
			return null;
		}

		List<RaceCardHorse> list = raceCardHorseService.getRaceCardHorseListByURL(raceInfo);

		if (list.size() == 0) {
			return null;
		}

		boolean cancelFlg = false;
		for (RaceCardHorse raceCardHorse : list) {
			if (BurubakaConstants.CANCEL.equals(raceCardHorse.getMemo())) {
				cancelFlg = true;
				break;
			}
		}

		if (cancelFlg) {
			log.info("キャンセルあり");
			// 登録馬更新
			raceCardHorseService.regist(list, raceInfo);
		}

		// レース情報更新
		raceInfo.setProgress(BurubakaConstants.PROGRESS_CANCEL);
		raceInfoService.regist(raceInfo);

		return null;
	}
}
